<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SiteTagSeeder extends Seeder
{
    // php artisan db:seed --class=SiteTagSeeder

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // 清空数据表 后在添加
        $time = time();
        $toDb = DB::table('site_tag');
        //$toDb->truncate();

        // 查询原来的数据
        $sql  = "select terms.term_id, terms.name, taxonomy.count from wp_terms terms
        join wp_term_taxonomy taxonomy on terms.term_id = taxonomy.term_id
        where taxonomy.taxonomy = 'post_tag';";
        $tags = DB::select($sql);
        $tags = json_decode(json_encode($tags), true);

        // 整理数据
        $all = [];
        foreach($tags as $_tag){
            $info = DB::table('site_tag')->where('id', $_tag['term_id'])->first();
            if($info){
                continue;
            }

            $all[] = $this->makeRow($_tag, $time);
        }

        // 执行
        $toDb->insert($all);
    }


    // 生成数据
    protected function makeRow($_tag, $time)
    {

        $_row = [
            'id'       => $_tag['term_id'],
            'en_title' => $_tag['name'],
            'cn_title' => '',
            'tc_title' => '',
            'number'   => $_tag['count'],
            'status'   => 1,
            'ctime'    => $time,
            'mtime'    => $time,
        ];

        return $_row;
    }

}
